<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/12
 * Time: 18:18
 */

namespace app\admin\controller;


use app\admin\behaviour\AdminAuth;
use app\admin\model\ApiResponse;
use app\admin\model\SysAdmin;
use app\admin\model\SysAdminMenu;
use app\admin\model\SysPermission;
use app\admin\model\SysRole;
use app\admin\lib\AdminController;
use app\api\model\user\Users;
use think\Db;
use think\db\Query;
use think\Request;

class Admins extends AdminController
{

    /**
     * 帐号列表
     * @return ApiResponse
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
            ['role', 'integer',],
        ]);

        $query = Db::table('sys_admin a');
        $query->join('customer_service s','s.admin_id=a.id','LEFT');
        $query->join('sys_role r','r.id=a.role_id');
        $query->join('users u','a.id=u.admin_id','LEFT');
        $query->where('a.id','>',1);
        $query->order('a.id','asc');
        $query->field('a.id,a.name,a.realname,a.nickname,a.avatar,a.role_id, s.admin_id, r.name role_name, u.mobile user_mobile');

        if (isset($form['role'])) {
            $query->where('a.role_id','=', $form['role']);
        }

        $re = $query->paginate($form['rows'] ?? 10,false, [
            'page' => $form['page']??1
        ])->toArray();

        return ApiResponse::success($re);
    }

    /**
     * 新建或修改帐号信息
     * @return ApiResponse
     */
    public function save() {
        $id = intval(input('post.id'));
        if ($id > 1) {
            $form = $this->getAndCheckForm([]);

            $data = ['id' => $id];

            if (!empty($form['password']))
                $data['password'] = passEncrypt($form['password']);

            foreach (['realname','nickname','role_id'] as $field)
                if (!empty($form[$field])) $data[$field] = $form[$field];

            $admin = SysAdmin::update($data);
        } else {
            $form = $this->getAndCheckForm([
                ['name','require',],
            ]);

            $name = $form['name'];
            $model = SysAdmin::get(['name' => $name]);
            if ($model)
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'账户已经存在！');

            $data = ['name' => $name,'role_id'=>1];

            if (!empty($form['password']))
                $data['password'] = passEncrypt($form['password']);

            foreach (['realname','nickname','role_id'] as $field)
                if (!empty($form[$field])) $data[$field] = $form[$field];

            $admin = SysAdmin::create($data);
        }
        if(isset($form['user_mobile'])){
            $this->adminUser($admin, $form['user_mobile']);
        }
        return ApiResponse::success();
    }

    /**
     * @param SysAdmin $admin
     * @param string $mobile
     * @return Users
     */
    private function adminUser(SysAdmin $admin, string $mobile) {

        $user = Users::get(['admin_id' => $admin->id]);
        if ($user) {
            if ($mobile == $user->mobile) return $user;
            $user->admin_id = 0;
            $user->save();
        }

        $user = Users::get(['mobile' => $mobile]);
        if ($user) {
            $user->admin_id = $admin->id;
            $user->save();
        } else {
            $user = Users::create(['mobile' => $mobile, 'admin_id' => $admin->id]);
            // 用户技能数据
            $curriculum_class = Db::table('curriculum_class')->select();
            $data = [];
            foreach ($curriculum_class as $val) {
                $data[] = [
                    'ability_user' => intval($user->id), // 用户id
                    'ability_curriculum_class' => intval($val['class_id']), // 课程分类
                    'ability_level' => 1 // 用户技能等级，默认初级 1=初级 2=中级 3=高级
                ];
            }
            Db::table('user_ability')->insertAll($data);
        }

        return $user;
    }

    /**
     * 删除帐号
     * @return ApiResponse
     */
    public function del() {

        $form = $this->getAndCheckForm([
            ['id','require|integer',],
        ]);

        $id = $form['id'];
        if (1 == $id) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'不能删除管理员');
        }

        $n = SysAdmin::destroy($id);
        if ($n > 0) AdminAuth::rmToken($id);

        return ApiResponse::success();
    }

    /**
     * 设置获取客服
     * @return ApiResponse
     */
    public function add_service() {

        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['cancel', 'require|integer',],
        ]);

        $id = intval($form['id'] ?? 0);
        $cancel = !empty($form['cancel']);

        SysAdmin::setService($id, $cancel);

        return ApiResponse::success();
    }

    /**
     * 角色列表
     * @return ApiResponse
     */
    public function role_list() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);

        $list = Db::table('sys_role')
            ->where('id','>',1)
            ->paginate($form['rows']??10, false, [
                'page' => $form['page']??1
            ])->toArray()
        ;

        return ApiResponse::success($list);
    }

    /**
     * 全部角色
     * @return ApiResponse
     */
    public function role_list_all() {
        $roles = SysRole::getAll();
        return ApiResponse::success($roles);
    }

    /**
     * 保存角色
     * @return ApiResponse
     */
    public function role_save() {
        $form = $this->getAndCheckForm([
            ['name', 'require',],
            ['remark', 'require',],
        ]);

        $data = [
            'name' => $form['name'],
            'remark' => $form['remark'],
        ];
        if (empty($form['id'])) {
            SysRole::create($data);
        } else {
            $data['id'] = $form['id'];
            SysRole::update($data);
        }

        return ApiResponse::success();
    }

    /**
     * 删除角色
     * @return ApiResponse
     */
    public function role_del() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',]
        ]);
        if (SysAdmin::checkRoleUsed($form['id']))
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'不能删除，正在使用');

        SysRole::destroy($form['id']);
        return ApiResponse::success();
    }

    /**
     * 获取菜单树
     * @return ApiResponse
     */
    public function menu_tree() {

        $form = $this->getAndCheckForm([
            ['role_id', 'integer',],
        ]);

        $role_id = intval($form['role_id'] ?? 0);
        if ($role_id > 1) {
            $menu = SysAdminMenu::menuTree($role_id);
        } else {
            $menu = SysAdminMenu::menuAllTree();
        }

        return ApiResponse::success($menu);
    }

    /**
     * 保存菜单
     * @return ApiResponse
     */
    public function menu_save() {

        $form = $this->getAndCheckForm([]);

        if (isset($form['id'])) {
            SysAdminMenu::update($form,[],SysAdminMenu::getSaveFields());
        } else {
            SysAdminMenu::create($form,SysAdminMenu::getSaveFields());
        }

        return ApiResponse::success();
    }

    /**
     * 删除菜单
     * @return ApiResponse
     */
    public function menu_del() {
        $id = input('id');
        SysAdminMenu::destroy($id);
        return ApiResponse::success();
    }

    /**
     * 保存角色的菜单配置
     * @return ApiResponse
     */
    public function menu_grant_save() {
        $form = $this->getAndCheckForm([
            ['role_id', 'require|integer',],
            ['menu_tree', 'require|array',],
        ]);

        SysAdminMenu::saveMenu(intval($form['role_id']), $form['menu_tree']);

        return ApiResponse::success($form);
    }

    public function permits_all() {
        $list = SysPermission::all(function(Query $query){
            $query->order('uri','asc');
        });
        return ApiResponse::success($list);
    }

    public function permits_menu() {
        $form = $this->getAndCheckForm([['menu_id','require|integer',]]);
        $list = SysPermission::getMenuPermits($form['menu_id']);
        return ApiResponse::success($list);
    }

    public function permits_menu_save() {
        $form = $this->getAndCheckForm([
            ['menu_id', 'require|integer',],
            ['permits', 'require|array',],
        ]);
        SysPermission::saveMenuPermits($form['menu_id'], $form['permits']);
        return ApiResponse::success();
    }
}